/**
 *	PEERCACHE.C - implementation of PEERCACHE.H
 *	Author: Fabio Garcia <fabio@blastpress.com>
 **/

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "peercache.h"

int add_peer(char *addr) {
	in_addr_t addr_i = inet_addr(addr);
	char out_file[] = "peers.cache";
	FILE *ofh = fopen(out_file, "a");
	if(ofh == NULL) return -1;
	fprintf(ofh, "%u\n", addr_i);
	fclose(ofh);
	return 0;
}

int remove_peer(char *addr) {
	in_addr_t addr_i = inet_addr(addr);
	char cache_file[] = "peer.cache";
	char tmp_file[] = "peer.cache.tmp";
	FILE *ifh = fopen(cache_file, "r");
	FILE *ofh = fopen(tmp_file, "w");
	while(!feof(ifh)) {
		in_addr_t peer;
		if(fscanf(ifh, "%u\n", &peer) != 1) {
			return -1;
		} else {
			if(peer != addr_i) fprintf(ofh, "%u\n", peer);
		}
	}
	fclose(ifh);
	fclose(ofh);
	remove(cache_file);
	rename(tmp_file, cache_file);
	return 0;
}

in_addr_t *get_peers() {
	in_addr_t peers[CACHE_SIZE];
	in_addr_t *peer_ptr = peers;
	char in_file[] = "peer.cache";
	FILE *ifh = fopen(in_file, "r");
	int count = 0;
	/** bzero(peers, CACHE_SIZE);**/
	while((count<CACHE_SIZE) && !feof(ifh)) {
		in_addr_t peer;
		if(fscanf(ifh, "%u\n", &peer) != 1) {
			break;
		} else {
			peers[count] = peer;
		}
		count++;
	}
	fclose(ifh);
	return peer_ptr;
}
